package com.ve.searcher


import com.ve.searcher.pojo.Responsejson
import com.ve.searcher.pojo.SearchPojo
import com.ve.searcher.service.LuceneService
import org.appsugar.archetypes.extension.getLogger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths

@RestController
class MainController {
    @Autowired
    val luceneService:LuceneService ?= null

    @RequestMapping(path = arrayOf("api/searchByString"))
    @ResponseBody
    @Throws(Exception::class)
    fun searchByString(searchpojo: SearchPojo): Responsejson {
        val result = Responsejson()
        try{
            val arrayList = luceneService!!.search(searchpojo)
            result.data = arrayList
            result.count = arrayList.size
        }catch (e:java.lang.Exception){
            result.code=2
            result.msg=e.message
            getLogger<MainController>().error(e.message,e)
        }
        return result
    }

    @RequestMapping(path = arrayOf("api/loadfile"))
    @ResponseBody
    @Throws(Exception::class)
    fun loadFile(filename: String, filepath: String): String {
        val xml = StringBuffer()
        val path = Paths.get(filepath + File.separator + filename);
//        val path = Paths.get(filepath)
        val lines = Files.readAllLines(path, StandardCharsets.UTF_8)
        lines.forEach { str -> xml.append(str).append("\r\n") }
        return xml.toString()
    }

    @RequestMapping(path = arrayOf("api/savefile"))
    @ResponseBody
    @Throws(Exception::class)
    fun saveFile(filename: String, filepath: String, content: String): Responsejson {
        val path = Paths.get(filepath + File.separator + filename)
        Files.write(path, content.toByteArray(StandardCharsets.UTF_8))
        val responsejson = Responsejson()
        return responsejson
    }
}